package com.storyroad.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;

import com.storyroad.utils.CreateNotification;
import com.storyroad.utils.DBConnection;
import com.storyroad.utils.TableNames;
import com.storyroad.utils.Utilities;

/**
 * Servlet implementation class RateStory
 */
public class RateStory extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public RateStory() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * Rates a story fragment on a scale of 1 to 10. Only the registered users can rate a story fragment. A user can
	 * rate a story fragment only once. If the rate operation is carried out successfully, the owner of the story fragment is sent a notification. 
	 * @param request HttpServletRequest object that contains data coming from front-end
	 * @param response HttpServletResponse object that contains data which is prepared after processing the incoming data
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		int u_id;
		int updateResult;
		int insertResult;
		int f_rating;
		int f_storyId;
		boolean rateSuccess;
		String username;
		String f_requestType = request.getParameter("request_type");
		PreparedStatement stmt = null;
		ResultSet rs;
		Connection conn = new DBConnection().connect();
		PrintWriter out = response.getWriter();

		if (f_requestType == null || !f_requestType.equals("Android")) {
			f_requestType = "Web";
		}
		if (conn == null) {
			out.println("Connection error");
		} else {
			try {
				CreateNotification newNotification = new CreateNotification();
				if (f_requestType.equals("Web")) {
					username = (String) request.getSession().getAttribute("username");
					// Check whether this action is performed by a registered user. If not, the user is redirected to the login page.					
					if (username == null) {
						response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + "/LoginPage.jsp"));
					}
				} else {
					username = request.getParameter("username");
				}

				u_id = Utilities.getUserId(conn, username);
				f_storyId = Integer.parseInt(request.getParameter("story_id"));
				// Check whether this user rated this fragment before.
				stmt = conn.prepareStatement("SELECT * FROM " + TableNames.RATING_TABLE + " WHERE u_id = ? and s_id = ?");
				stmt.setInt(1, u_id);
				stmt.setInt(2, f_storyId);
				rs = stmt.executeQuery();
				if (rs.next()) {
					// If the user rated this fragment before then do not carry out the rating operation.
					rateSuccess = false;
				} else {
					// If it is the first time this user is rating this fragment
					f_rating = Integer.parseInt(request.getParameter("rating"));
					stmt = conn.prepareStatement("UPDATE "
							+ TableNames.STORIES_TABLE
							+ " SET totalRating = totalRating + ?"
							+ ", ratingCount = ratingCount + ? WHERE s_id = ?");
					stmt.setInt(1, f_rating);
					stmt.setInt(2, 1);
					stmt.setInt(3, f_storyId);
					updateResult = stmt.executeUpdate();
					stmt = conn.prepareStatement("INSERT INTO "
							+ TableNames.RATING_TABLE
							+ "(u_id,s_id,rating) VALUES(?,?,?)");
					stmt.setInt(1, u_id);
					stmt.setInt(2, f_storyId);
					stmt.setInt(3, f_rating);
					insertResult = stmt.executeUpdate();
					/*
					 * If the rating is done successfully, a notification for the owner of the story fragment is created.
					 * Please refer to CreateNotification.java in utils package to get a more detailed description of the
					 * notification system.
					 */
					if (insertResult == 1 && updateResult == 1) {
						rateSuccess = true;
						newNotification.createRateNotification(u_id, f_storyId);
					} else {
						rateSuccess = false;
					}
				}
				JSONObject rateResultJsonObject = new JSONObject();
				response.setContentType("application/json");
				try {
					rateResultJsonObject.put("rateSuccess", rateSuccess);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				out.print(rateResultJsonObject.toString());
			} catch (SQLException e) {
				out.print(e.getMessage());
				e.printStackTrace();
			}
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		processRequest(request, response);
	}

}
